#pragma once
#include <iostream>
#include <vector>
#include "InterAddr.hpp"
#include "Log.hpp"
#include "mutex.hpp"

using namespace LogModule;
using namespace MutexModule;

/* 路由服务类 */
class Route
{
private:
    bool IsExit(const InterAddr& peer)
    {
        /* 变量比较_online_users */
        for(auto &user : _online_users)
        {
            if(user == peer) return true;
        }
        return false;
    }

    void AddUser(const InterAddr& peer)
    {
        LOG(LogLevel::INFO) << "Add a new user!";
        _online_users.push_back(peer);
    }

    void DeleteUser(const InterAddr& peer)
    {
        for(auto it = _online_users.begin(); it != _online_users.end(); ++it)
        {
            if(*it == peer)
            {
                LOG(LogLevel::INFO) << "Delete a online user!";
                _online_users.erase(it);
                break;
            }
        }
    }

public:
    Route()
    {
    }

    void MessageRoute(int sockfd, const std::string & message, InterAddr& peer)
    {
        LockGuard lockguard(_lock); // 上锁的原因 ???
        
        /* 判断路由用户是否存在，如果不存在添加用户 */
        if(!IsExit(peer))
        {
            AddUser(peer);
        }

        /* 为发送的信息加上指定的用户name(ip + port) */
        std::string EchoMessage = peer.AddrName() + " # " + message;

        /* 转发给所有在线用户列表中的用户 */
        for(auto &user : _online_users)
        {
            LOG(LogLevel::DEBUG) << "Route to: " << user.AddrName(); 
            sendto(sockfd, EchoMessage.c_str(), EchoMessage.size(), 0, (const sockaddr*)&user.GetAddr(), user.Len());
        }

        // 这个用户一定已经在线了
        if (message == "QUIT")
        {
            LOG(LogLevel::INFO) << "Delete a online user: " << peer.AddrName();
            DeleteUser(peer);
        }
    }

    ~Route() 
    {
    }

private:
    std::vector<InterAddr> _online_users;
    Mutex _lock;
};